<template>
	<view class="upload">
		<view class="upload-content" v-show="isLogin">
			<view class="form">
				<u--form labelPosition="left" :model="formData" :rules="rules" ref="form">
					<!-- APP名称 -->
					<u-form-item label="APP名称" labelWidth="160rpx" prop="name" borderBottom required>
						<u--input v-model="formData.name" border="none" placeholder="请搜索" @input="search"></u--input>
					</u-form-item>

					<!-- 分类 -->
					<u-form-item
						v-if="!showSearch"
						label="分类"
						labelWidth="160rpx"
						prop="classification"
						borderBottom
						required
						@click="showCategories = true"
					>
						<u--input
							v-if="!chooseCategories.length"
							v-model="formData.classification"
							border="none"
							placeholder="请选择"
							readonly
						></u--input>
						<view class="tags_list" v-else>
							<view class="tag" v-for="(item, index) in chooseCategories" :key="item.id">
								<Tag :text="item.name"></Tag>
							</view>
						</view>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>

					<!-- 平台 -->
					<u-form-item
						v-if="!showSearch"
						label="平台"
						labelWidth="160rpx"
						prop="platform"
						borderBottom
						required
						@click="showPlatforms = true"
					>
						<u--input
							v-if="!choosePlatforms.length"
							v-model="formData.platform"
							placeholder="请选择"
							border="none"
							readonly
						></u--input>
						<view class="tags_list" v-else>
							<view class="tag" v-for="(item, index) in choosePlatforms" :key="item.id">
								<Tag :text="item.name"></Tag>
							</view>
						</view>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
				</u--form>
			</view>

			<view v-show="!showSearch">
				<!-- 上传列表组件 -->
				<view class="upload_pic">
					<UploadList v-if="refresh" :assetTags="assetTags" @upload="uploadResult"></UploadList>
				</view>
				<!-- 保存确定按钮 -->
				<view><button class="btn" plain :loading="submitLoading" @click="submit">提交</button></view>
			</view>

			<!-- 搜索列表 -->
			<!-- <uni-transition :show="formData.name && showSearch" :mode="showSearch ? 'fade-down' : ''" duration="1000"> -->
			<view v-show="formData.name && showSearch">
				<view class="loading" v-if="searchLoading"><u-loading-icon></u-loading-icon></view>
				<view class="articles_list" v-else>
					<view
						class="articles_item"
						v-for="(item, index) in articlesList"
						:key="item.id"
						@click="getAppName(item)"
					>
						<ListItem :title="item.title"></ListItem>
					</view>
				</view>
			</view>
			<!-- </uni-transition> -->

			<!-- 选择分类 -->
			<!-- <TagsPopup
				ref="categoryPopup"
				v-if="showCategories"
				:show="showCategories"
				:chooses="chooseCategories"
				:options="categories"
				@finish="
					v => {
						finish(v, 'categories');
					}
				"
				@close="close('categories')"
			/> -->

			<!-- <TagsPopup
				v-if="showPlatforms"
				:show="showPlatforms"
				:chooses="choosePlatforms"
				:options="platforms"
				@finish="
					v => {
						finish(v, 'platforms');
					}
				"
				@close="close('platforms')"
			/> -->

			<!-- 选择分类 -->
			<u-picker
				:show="showCategories"
				:columns="[categories]"
				keyName="name"
				@confirm="
					v => {
						finish(v, 'categories');
					}
				"
				@cancel="showCategories = false"
				closeOnClickOverlay
				@close="showCategories = false"
			></u-picker>

			<!-- 选择平台 -->
			<u-picker
				:show="showPlatforms"
				:columns="[platforms]"
				keyName="name"
				@confirm="
					v => {
						finish(v, 'platforms');
					}
				"
				@cancel="showPlatforms = false"
				closeOnClickOverlay
				@close="showPlatforms = false"
			></u-picker>
		</view>

		<login v-if="!isLogin" isComponent />
	</view>
</template>

<script>
import UploadList from '@/components/UploadList/UploadList.vue';
import api from '@/common/api.js';
import ListItem from '@/components/ListItem.vue';
import TagsPopup from '@/components/TagsPopup.vue';
import login from '@/pages/loginWays/loginWays.vue';
import Tag from '@/components/Tag/Tag.vue';
export default {
	components: {
		UploadList,
		ListItem,
		TagsPopup,
		login,
		Tag
	},
	data() {
		return {
			formData: {
				name: '',
				classification: '',
				platform: ''
			},
			rules: {
				name: {
					type: 'string',
					required: true,
					message: '请填写APP名称',
					trigger: ['blur', 'change']
				},
				classification: {
					validator: (rule, value, callback) => {
						if (this.chooseCategories.length) {
							return true;
						} else {
							return false;
						}
					},
					message: '请选择分类',
					trigger: ['change', 'blur']
				},
				platform: {
					validator: (rule, value, callback) => {
						if (this.choosePlatforms.length) {
							return true;
						} else {
							return false;
						}
					},
					message: '请选择平台',
					trigger: ['change', 'blur']
				}
			},

			assetTags: [],
			categories: [],
			platforms: [],

			showCategories: false,
			showPlatforms: false,

			articlesList: [], // 文章列表

			showSearch: false, // 展示搜索列表

			searchLoading: false,

			timeout: null,

			chooseCategories: [], // 已选的分类
			chooseCategorieId: '', // 已选的分类id
			choosePlatforms: [], // 已选的平台
			choosePlatformId: '', // 已选的平台id

			fileList: [],
			assets: [], // 提交的图片信息

			submitLoading: false,

			refresh: true
		};
	},
	onLoad() {
		console.log('onLoad');
		this.assetTags = getApp().globalData.assetTags;
		this.categories = getApp().globalData.categories;
		this.platforms = getApp().globalData.platforms;
	},
	onReady() {
		console.log('onReady');
		if (this.$refs.form) {
			this.$refs.form.setRules(this.rules);
		}
	},
	onShow() {
		// console.log('onShow')
		// if (this.isLogin && this.$refs.form) {
		// 	this.formData = {
		// 		name: '',
		// 		classification: '',
		// 		platform: ''
		// 	};
		// 	this.$refs.form.clearValidate();
		// }
	},
	onPullDownRefresh() {
		this.init();
	},
	computed: {
		isLogin() {
			return this.$store.state.isLogin;
		},
		userInfo() {
			return this.$store.state.userinfo;
		}
	},
	methods: {
		init() {
			this.formData.name = '';
			this.chooseCategories = [];
			this.choosePlatforms = [];
			this.assets = [];
			this.choosePlatformId = '';
			this.$refs.form.clearValidate();
			this.refresh = false;
			this.$nextTick(() => {
				this.refresh = true;
			});
			uni.stopPullDownRefresh();
		},

		// 搜索
		search() {
			this.showSearch = true;
			clearTimeout(this.timeout);
			// this.timeout = null;
			this.timeout = setTimeout(() => {
				this.articlesList = [];
				this.getArticlesList(this.formData.name);
			}, 500);

			if (!this.formData.name) {
				// this.articlesList = [];
				this.showSearch = false;
			}
		},

		// 在搜索列表选择app名称后，获取到app的信息
		getAppName(item) {
			// console.log('item ==>', item);
			this.formData.name = item.title;
			this.chooseCategories = [];
			// this.choosePlatforms = [];
			item.tags.forEach(v => {
				if (v.category.name == '分类') {
					this.chooseCategories.push({ id: v.id, name: v.name });
				}
				// else if (v.category.name == 'platforms') {
				// 	this.choosePlatforms.push({id: v.id, name: v.name});
				// }
			});
			this.showSearch = false;
		},

		// 获取文章列表
		async getArticlesList(keyword) {
			if (!keyword) return;
			// 判断token字符串是否存在
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				console.log('token不存在');
				return uni.navigateTo({
					url: '../loginWays/loginWays'
				});
			}

			this.searchLoading = true;
			try {
				let res = await this.$ajax({
					url: api.get_article_list,
					data: {
						_keyword: keyword
					},
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				// console.log('searchRes ==>', res);
				this.articlesList = res.data.data;
				// this.articlesList = data.map(item => {
				// 	return item.title;
				// })
				this.$nextTick(() => {
					this.searchLoading = false;
				});
				if (this.articlesList.length <= 0) {
					this.showSearch = false;
				}
			} catch (e) {
				console.log(e);
				this.searchLoading = false;
			}
		},

		// 上传图片成功后触发事件
		async uploadResult(fileList) {
			// console.log('成功后的图片列表 ==>', fileList);
			this.assets = [];
			this.fileList = fileList;
			// fileList.forEach(item => {
			// 	let tags = [];
			// 	tags = item.tagList.map(v => {
			// 		return { name: v.name };
			// 	});
			// 	this.assets.push({
			// 		asset_id: item.id,
			// 		md5: item.md5,
			// 		url: item.path,
			// 		tags
			// 	});
			// });
		},

		// 上传图片
		uploadFilePromise(url) {
			// console.log(this.fileList);
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: this.$baseURL + api.upload_url,
					filePath: url,
					name: 'file',
					success: res => {
						// console.log('res ==>', res);
						let result = JSON.parse(res.data);
						// console.log('resImg ==>', result);
						if (result.code == '400') {
							uni.showToast({
								title: result.message,
								icon: 'none'
							});
							resolve(false);
							return;
						}
						let data = result.data;
						delete data.size;
						resolve(data);
					},
					fail: e => {
						console.log(e);
					}
				});
			});
		},

		// 提交
		async submit() {
			let isPass = await this.validateForm();
			if (!isPass) {
				return false;
			}

			// 判断token字符串是否存在
			let tokenString = uni.getStorageSync('access_token');
			if (!tokenString) {
				console.log('token不存在');
				return uni.showToast({
					title: '请登录',
					duration: 1000,
					icon: 'error',
					complete() {
						setTimeout(() => {
							uni.navigateTo({
								url: '../loginWays/loginWays'
							});
						}, 1000);
					}
				});
			}

			this.submitLoading = true;

			let tags = this.chooseCategories.map(item => {
				return item.id;
			});
			// console.log('tags ==>', tags);
			try {
				// 上传图片
				for (let i = 0; i < this.fileList.length; i++) {
					let result = await this.uploadFilePromise(this.fileList[i].thumb);
					if (!result) {
						return;
					}
					let tags = [];
					if (this.fileList[i].tagList.length) {
						tags = this.fileList[i].tagList.map(v => {
							return { name: v.name };
						});
					}
					this.assets.push({
						asset_id: result.id,
						md5: result.md5,
						url: result.path,
						tags
					});
				}

				if (this.fileList.length !== this.assets.length) {
					return false;
				}

				// 提交表单
				let res = await this.$ajax({
					url: api.save_article,
					method: 'POST',
					data: {
						title: this.formData.name,
						assets: this.assets,
						tags,
						platform: this.choosePlatformId
					},
					header: {
						Authorization: 'Bearer ' + tokenString
					}
				});
				this.submitLoading = false;
				// this.init();
				uni.showToast({
					title: '提交成功',
					icon: 'success',
					duration: 1000
				});
				setTimeout(() => {
					uni.reLaunch({
						url: '../index/index'
					});
				}, 1000);
				// console.log('submitRes ==>', res);
			} catch (e) {
				console.log(e);
				this.submitLoading = false;
			}
		},

		// 表单验证的方法
		validateForm() {
			return new Promise((resolve, reject) => {
				this.$refs.form
					.validate()
					.then(res => {
						resolve(true);
					})
					.catch(err => {
						resolve(false);
					});
			});
		},

		// 弹出层选择完成触发事件
		finish(data, type) {
			// console.log('data ==>', data);
			// console.log('type ==>', type);
			if (type == 'categories') {
				this.chooseCategories = data.value;
				this.chooseCategorieId = data.value[0].id;
				this.$refs.form.validateField('classification');
				this.showCategories = false;
			} else {
				this.choosePlatforms = data.value;
				this.choosePlatformId = data.value[0].id;
				this.$refs.form.validateField('platform');
				this.showPlatforms = false;
			}
		},

		// 关闭弹出层
		close(type) {
			if (type == 'categories') {
				this.showCategories = false;
			} else {
				this.showPlatforms = false;
			}
		}
	}
};
</script>

<style lang="scss">
.upload {
	.upload-content {
		padding: 0 32rpx 20rpx;
	}

	.upload_pic {
		margin: 40rpx 0 20rpx;
	}

	.loading {
		height: 90vh;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.tags_list {
		padding-top: 10rpx;
	}
	.tag {
		display: inline-block;
		margin: 0 20rpx 10rpx 0;
	}
	.btn {
		background-color: #fff;
		color: #333333;
		font-weight: 700;
		border: 2rpx solid #e7e7e7;
		border-radius: 18rpx;
	}
}
</style>
